#include "Metgine/UI/UIManager.hpp"


namespace Metgine
{
namespace UI
{

UIManager::UIManager()
{
    m_inputHook = NULL;
}

UIManager::~UIManager()
{
    RemoveAllWidgets();
}

bool UIManager::Exists(Widget* widget)
{
    std::list<Widget*>::iterator i = m_widgets.begin();

    while (i != m_widgets.end())
    {
        if (*i == widget)
            return true;
        i ++;
    }
    return false;

}

void UIManager::AddWidget(Widget* widget)
{

    if (!Exists(widget))
    {
        // Set self as the widget owner
        widget->SetOwner(this);

        // Add the widget
        m_widgets.insert(m_widgets.end(), widget);
    }
}

void UIManager::RemoveWidget(Widget* widget)
{
    m_widgets.remove(widget);
}

void UIManager::RemoveWidgetsInGroup(int group)
{
    if (group == Group::All)
    {
        RemoveAllWidgets();
    }
    else if (group != Group::None)
    {
        std::list<Widget*>::iterator i = m_widgets.begin();

        while (i != m_widgets.end())
        {
            Widget* w = (*i);

            if (w->GetGroup() & group)
            {
                delete w;
                w = NULL;
                i = m_widgets.erase(i);
            }
            else
                i++;
        }
    }
}

void UIManager::RemoveAllWidgets()
{
    std::list<Widget*>::iterator i = m_widgets.begin();

    while (i != m_widgets.end())
    {

        delete *i;
        *i = NULL;
        i ++;

    }

    m_widgets.clear();
}

void UIManager::Update(float elapsedTime)
{
    std::list<Widget*>::iterator i = m_widgets.begin();

    while (i != m_widgets.end())
    {
        (*i)->Update(elapsedTime);

        i++;
    }
}

void UIManager::Render()
{
    std::list<Widget*>::iterator i = m_widgets.begin();

    while (i != m_widgets.end())
    {
        Widget* w = (*i);
        if (w->IsVisible())
            w->Render();
        i++;
    }
}

Widget* UIManager::operator[](const std::string& name)
{
    return GetWidget(name);
}

Widget* UIManager::operator[](int index)
{
    return GetWidget(index);
}

Widget* UIManager::GetWidget(const std::string& name)
{
    std::list<Widget*>::iterator i = m_widgets.begin();

    while (i != m_widgets.end())
    {
        Widget* w = *i;

        if (w->GetName() == name)
            return w;

        i ++;
    }

    return NULL;
}

Widget* UIManager::GetWidget(int index)
{
    std::list<Widget*>::iterator iter = m_widgets.begin();
    std::advance(iter, index);
    return *iter;
}

bool UIManager::KeyDown(sf::Key::Code key, bool shift, bool control, bool alt)
{
	if (m_inputHook)
		return m_inputHook->KeyDown(key, shift, control, alt);

	return false;
}

bool UIManager::KeyUp(sf::Key::Code key, bool shift, bool control, bool alt)
{
	if (m_inputHook)
		return m_inputHook->KeyUp(key, shift, control, alt);

	return false;
}

void UIManager::SetInputHook(Widget* widget)
{
	m_inputHook = widget;
}

}; // UI
}; // Metgine
